package com.example.service;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User findUserWithRolesByUsername(String username) {
        return userMapper.findUserWithRolesByUsername(username);
    }

    public List<User> findUsersWithRolesAndMenusByCondition(String username, String email,
                                                            Integer status, Integer page, Integer pageSize) {
        Integer offset = (page - 1) * pageSize;
        return userMapper.findUsersWithRolesAndMenusByCondition(username, email, status, offset, pageSize);
    }

    public Long countUsersByCondition(String username, String email, Integer status) {
        return userMapper.countUsersByCondition(username, email, status);
    }

    // 任务四：更新用户角色 - 增强事务管理
    @Transactional(rollbackFor = Exception.class)
    public void updateUserRoles(Long userId, List<Long> roleIds) {
        // 删除用户现有角色
        userMapper.deleteUserRoles(userId);

        // 添加新角色
        if (roleIds != null && !roleIds.isEmpty()) {
            for (Long roleId : roleIds) {
                userMapper.addUserRole(userId, roleId);
            }
        }
    }
}
